import 'package:flutter/material.dart';

void main() {
  runApp(HeroDemoApp());
}

class HeroDemoApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Complex Hero Animation Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: PhotoGalleryScreen(),
    );
  }
}

// 照片数据模型
class Photo {
  final String id;
  final String title;
  final String imageUrl;
  final String description;
  final String author;
  final DateTime date;

  Photo({
    required this.id,
    required this.title,
    required this.imageUrl,
    required this.description,
    required this.author,
    required this.date,
  });
}

// 照片库屏幕
class PhotoGalleryScreen extends StatelessWidget {
  // 示例照片数据
  final List<Photo> photos = [
    Photo(
      id: '1',
      title: 'Mountain Landscape',
      imageUrl: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4',
      description: 'Beautiful mountain landscape with snow peaks and blue sky.',
      author: 'John Smith',
      date: DateTime(2023, 5, 15),
    ),
    Photo(
      id: '2',
      title: 'Ocean Waves',
      imageUrl: 'https://images.unsplash.com/photo-1505228395891-9a51e781709d',
      description: 'Powerful ocean waves crashing against the rocks on a sunny day.',
      author: 'Emily Johnson',
      date: DateTime(2023, 6, 22),
    ),
    Photo(
      id: '3',
      title: 'Forest Path',
      imageUrl: 'https://images.unsplash.com/photo-1448375240586-882707db888b',
      description: 'Mysterious forest path leading into the unknown with sunlight filtering through trees.',
      author: 'Michael Brown',
      date: DateTime(2023, 7, 10),
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Photo Gallery'),
      ),
      body: GridView.builder(
        padding: EdgeInsets.all(8.0),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          crossAxisSpacing: 8.0,
          mainAxisSpacing: 8.0,
        ),
        itemCount: photos.length,
        itemBuilder: (context, index) {
          return PhotoGridItem(photo: photos[index]);
        },
      ),
    );
  }
}

// 照片网格项
class PhotoGridItem extends StatelessWidget {
  final Photo photo;

  const PhotoGridItem({Key? key, required this.photo}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => PhotoDetailScreen(photo: photo),
          ),
        );
      },
      child: Hero(
        tag: 'photo-${photo.id}', // Hero tag 必须唯一且在两个页面中一致
        child: Material(
          borderRadius: BorderRadius.circular(12.0),
          clipBehavior: Clip.hardEdge,
          child: Stack(
            fit: StackFit.expand,
            children: [
              Image.network(
                photo.imageUrl,
                fit: BoxFit.cover,
                loadingBuilder: (context, child, loadingProgress) {
                  if (loadingProgress == null) return child;
                  return Center(
                    child: CircularProgressIndicator(
                      value: loadingProgress.expectedTotalBytes != null
                          ? loadingProgress.cumulativeBytesLoaded /
                              loadingProgress.expectedTotalBytes!
                          : null,
                    ),
                  );
                },
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    color: Colors.grey[300],
                    child: Icon(
                      Icons.error_outline,
                      color: Colors.red,
                    ),
                  );
                },
              ),
              // 渐变遮罩，使文字更易读
              Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Colors.transparent,
                      Colors.black.withOpacity(0.7)
                    ],
                  ),
                ),
              ),
              // 标题文字
              Align(
                alignment: Alignment.bottomLeft,
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(
                    photo.title,
                    style: TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 16.0,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// 照片详情屏幕
class PhotoDetailScreen extends StatelessWidget {
  final Photo photo;

  const PhotoDetailScreen({Key? key, required this.photo}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          // 使用 Hero 实现图片的共享过渡动画
          SliverAppBar(
            expandedHeight: 300.0,
            pinned: true,
            flexibleSpace: FlexibleSpaceBar(
              background: Hero(
                tag: 'photo-${photo.id}', // 与前一个页面相同的 tag
                child: Image.network(
                  photo.imageUrl,
                  fit: BoxFit.cover,
                  loadingBuilder: (context, child, loadingProgress) {
                    if (loadingProgress == null) return child;
                    return Center(
                      child: CircularProgressIndicator(
                        value: loadingProgress.expectedTotalBytes != null
                            ? loadingProgress.cumulativeBytesLoaded /
                                loadingProgress.expectedTotalBytes!
                            : null,
                      ),
                    );
                  },
                  errorBuilder: (context, error, stackTrace) {
                    return Container(
                      color: Colors.grey[300],
                      child: Icon(
                        Icons.error_outline,
                        color: Colors.red,
                      ),
                    );
                  },
                ),
              ),
            ),
          ),
          SliverToBoxAdapter(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    photo.title,
                    style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                          fontWeight: FontWeight.bold,
                        ),
                  ),
                  SizedBox(height: 8.0),
                  Row(
                    children: [
                      Icon(Icons.account_circle, size: 16.0),
                      SizedBox(width: 4.0),
                      Text(photo.author),
                      SizedBox(width: 16.0),
                      Icon(Icons.calendar_today, size: 16.0),
                      SizedBox(width: 4.0),
                      Text(
                        '${photo.date.year}-${photo.date.month}-${photo.date.day}',
                      ),
                    ],
                  ),
                  SizedBox(height: 16.0),
                  Text(
                    'Description',
                    style: Theme.of(context).textTheme.titleMedium?.copyWith(
                          fontWeight: FontWeight.bold,
                        ),
                  ),
                  SizedBox(height: 8.0),
                  Text(
                    photo.description,
                    style: Theme.of(context).textTheme.bodyMedium,
                  ),
                  SizedBox(height: 24.0),
                  // 相关照片部分也使用 Hero 动画
                  Text(
                    'Related Photos',
                    style: Theme.of(context).textTheme.titleMedium?.copyWith(
                          fontWeight: FontWeight.bold,
                        ),
                  ),
                  SizedBox(height: 8.0),
                ],
              ),
            ),
          ),
          // 相关照片列表
          SliverToBoxAdapter(
            child: SizedBox(
              height: 120.0,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                itemCount: 5, // 模拟5个相关照片
                itemBuilder: (context, index) {
                  return Padding(
                    padding: const EdgeInsets.only(right: 8.0),
                    child: Hero(
                      tag: 'related-photo-$index-${photo.id}',
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(8.0),
                        child: Image.network(
                          'https://picsum.photos/seed/${index+10}/300/200',
                          width: 120.0,
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
          ),
          SliverToBoxAdapter(
            child: SizedBox(height: 16.0),
          ),
        ],
      ),
    );
  }
}
